$(function () {
    // var key = getcookie('key');
    // if (key == '') {
    //     window.location.href = WapSiteUrl + '/tmpl/member/login.html';
    // } else {
        //初始化页面数据
        function initCartList() {
            $.ajax({
                url: ApiUrl + "/user/eb/getShoppingCart",
                type: "post",
                dataType: "json",
                success: function (result) {
                    console.log(result);
                    
                    // if (checklogin(result.login)) {
                        if (result.rspCode==0&&result.shoppingCart!=null) {

                            var sum = 0;
                            for (var i = 0; i < result.shoppingCart.length; i++) {
                                sum+=result.shoppingCart[i].cpackage.money*result.shoppingCart[i].num;
                            };
                            result.sum = parseFloat(sum).toFixed(2);
                            result.WapSiteUrl = WapSiteUrl;
                            var html = template.render('cart-list', result);
                            $("#cart-list-wp").html(html);
                            //删除购物车
                            $(".cart-list-del").click(delCartList);
                            //购买数量，减
                            $(".minus-wp").click(minusBuyNum);
                            //购买数量加
                            $(".add-wp").click(addBuyNum);
                            //去结算
                            $(".goto-settlement").click(goSettlement);
                            $(".buy-num").blur(buyNumer);
                            // $(".buy-num").keyup(changeNum);
                        } 
                        // else {
                        //     alert(result.rspDesc);
                        // }
                    // }
                }
            });
        }

        initCartList();
        //删除购物车
        function delCartList() {
            var ele = $(this);
            var cart_id = $(this).attr('cart_id');
            var quantity = -$(this).parent().find('.buy-num').val();
            $.ajax({
                url: ApiUrl + "/user/eb/updateShoppingCartNum/"+cart_id,
                type: "post",
                data: {id:cart_id, num: quantity},
                dataType: "json",
                success: function (res) {
                    console.log(res)
                    // if (checklogin(res.login)) {
                        if (res.rspCode==0) {
                            ele.parents('.cart-list-item').remove();
                            var goodsTotal = $(".goods-total-price");
                            var totalPrice = parseFloat("0.00");
                            for (var i = 0; i < goodsTotal.length; i++) {
                                totalPrice += parseFloat($(goodsTotal[i]).html());
                            }
                            $(".total_price").html("￥" + totalPrice.toFixed(2));
                        } else {
                            $.sDialog({
                                skin: "red",
                                content: res.rspDesc,
                                okBtn: false,
                                cancelBtn: false
                            });
                        }
                    // }
                }
            });
        }

        //当输入数量发生改变时调用
        function changeNum() {
            var self = this;
            var sPrents = $(self).parents(".cart-litemw-cnt")
            var cart_id = sPrents.attr("cart_id");
            var numInput = sPrents.find(".buy-num");

            //为空,输入不为数字
            var pattern = /^[0-9]*$/;
            if (numInput.val() == '' || !numInput.val().match(pattern)) {
                numInput.val(1);
            }

            var buynum = parseFloat(numInput.val());

            //小于1
            if (buynum < 1) {
                numInput.val(1);
            }
            var buynum = parseInt(numInput.val());
            var quantity = buynum;
            $.ajax({
                url: ApiUrl + "/index.php?act=member_cart&op=cart_edit_quantity",
                type: "post",
                data: {key: key, cart_id: cart_id, quantity: quantity},
                dataType: "json",
                success: function (res) {
                    if (checklogin(res.login)) {
                        if (!res.datas.error) {
                            numInput.val(quantity);
                            sPrents.find(".goods-total-price").html(res.datas.total_price);
                            var goodsTotal = $(".goods-total-price");
                            var totalPrice = parseFloat("0.00");
                            for (var i = 0; i < goodsTotal.length; i++) {
                                totalPrice += parseFloat($(goodsTotal[i]).html());
                            }
                            $(".total_price").html("￥" + totalPrice.toFixed(2));
                        } else {
                            $.sDialog({
                                skin: "red",
                                content: res.datas.error,
                                okBtn: false,
                                cancelBtn: false
                            });
                        }
                    }
                }
            });
        }

        //购买数量减
        function minusBuyNum() {
            var self = this;
            editQuantity(self, "minus");
        }

        //购买数量加
        function addBuyNum() {
            var self = this;
            editQuantity(self, "add");
        }

        //购买数量增或减，请求获取新的价格
        function editQuantity(self, type) {
            var sPrents = $(self).parents(".cart-litemw-cnt")
            var cart_id = sPrents.attr("cart_id");
            var numInput = sPrents.find(".buy-num");
            var buynum = parseInt(numInput.val());

            var quantity = 1;
            if (type == "add") {
                quantity = 1;
                // 
            } else {
                if (buynum > 1) {
                    quantity = -1;
                } else {
                    $.sDialog({
                        skin: "red",
                        content: '购买数目必须大于1',
                        okBtn: false,
                        cancelBtn: false
                    });
                    return;
                }
            }
            $.ajax({
                url: ApiUrl + "/user/eb/updateShoppingCartNum/"+cart_id,
                type: "post",
                data: {id:cart_id, num: quantity},
                dataType: "json",
                success: function (res) {
                    console.log(res)
                    // if (checklogin(res.login)) {
                        if (res.rspCode==0) {
                            numInput.val(buynum+quantity);
                            var tempTotalPrice = (buynum+quantity)*(parseFloat(sPrents.find('.cellPrice').text()));
                            sPrents.find(".goods-total-price").html(tempTotalPrice);
                            var goodsTotal = $(".goods-total-price");
                            var totalPrice = parseFloat("0.00");
                            for (var i = 0; i < goodsTotal.length; i++) {
                                totalPrice += parseFloat($(goodsTotal[i]).html());
                            }
                            $(".total_price").html("￥" + totalPrice.toFixed(2));
                        } else {
                            $.sDialog({
                                skin: "red",
                                content: res.rspDesc,
                                okBtn: false,
                                cancelBtn: false
                            });
                        }
                    // }
                }
            });
        }

        //去结算
        function goSettlement() {
            //购物车ID
            // var key = getcookie('doutingshop');//登录标记
            // if (key == '') {
            //     window.location.href = WapSiteUrl + '/tmpl/member/login.html';
            // } else {
                // var cartIdArr = [];
                // var cartIdEl = $(".cart-litemw-cnt");
                // for (var i = 0; i < cartIdEl.length; i++) {
                //     var cartId = $(cartIdEl[i]).attr("cart_id");
                //     var cartNum = parseInt($(cartIdEl[i]).find(".buy-num").val());
                //     var cartIdNum = cartId + "|" + cartNum;
                //     cartIdArr.push(cartIdNum);
                // }
                // var cart_id = cartIdArr.toString();
                var carts = [];
                $('.cart-litemw-cnt').each(function(index,domEle){
                    var cart = {};
                    var cpackage = {};
                    cpackage.id = $(this).attr('cart_id');
                    cart.cpackage = cpackage;
                    cart.num = $(this).find('.buy-num').val();
                    carts.push(cart);
                });
                $.ajax({
                    url: ApiUrl + "/user/eb/saveOrder",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(carts),
                    dataType: "json",
                    success: function (res) {
                        // console.log(res)
                        checklogin(res.rspCode);
                        // if (checklogin(res.login)) {
                        if (res.rspCode==0) {
                            window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+res.orderId;
                        }else {
                            $.sDialog({
                                skin: "red",
                                content: res.rspDesc,
                                okBtn: false,
                                cancelBtn: false
                            });
                        }
                        // }
                    }
                });
            // }
        }
        //验证
        $.sValid.init({
            rules: {
                buynum: "digits"
            },
            messages: {
                buynum: "请输入正确的数字"
            },
            callback: function (eId, eMsg, eRules) {
                if (eId.length > 0) {
                    var errorHtml = "";
                    $.map(eMsg, function (idx, item) {
                        errorHtml += "<p>" + idx + "</p>";
                    });
                    $.sDialog({
                        skin: "red",
                        content: errorHtml,
                        okBtn: false,
                        cancelBtn: false
                    });
                }
            }
        });
        function buyNumer() {
            $.sValid();
        }
    // }
});